package com.cooper.controllers;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.cooper.core.JsonResult;
import com.cooper.core.MinasPropertyHandler;
import com.cooper.util.HttpUtils;
import com.cooper.util.StringUtils;
import com.cooper.vo.UploadVo;
import com.google.common.collect.Maps;

import net.paoding.rose.web.Invocation;
import net.paoding.rose.web.annotation.rest.Get;
import net.paoding.rose.web.annotation.rest.Post;
import net.paoding.rose.web.portal.Portal;

public class UploadController {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private MinasPropertyHandler minasPropertyHandler;
	
	@Template(title="上传文件")
	@Get
	public String execute(Invocation inv, Portal portal){
		return "dev/Upload";
	}
	
	@Get("image")
	public String uploadImage(Invocation inv, UploadVo uploadVo){
		inv.addModel("uploadVo", uploadVo);
		return "dev/UploadImage";
	}
	
	@Post
	public Object startUpload(Invocation inv, MultipartFile file, UploadVo uploadVo) throws Throwable {
		JsonResult json = new JsonResult();
		if(0 == file.getSize()){
			return "@Please Select File First.";
		}
		logger.info("Start to upload file[{}].", file.getOriginalFilename());

		Map<String, String> params = Maps.newConcurrentMap();
		params.put("appKey", "chongzhi");
		
		String strResponse = HttpUtils.doUploadFile(this.minasPropertyHandler.getFileServer() + "upload", params, "file", 
				file.getOriginalFilename(), file.getContentType(), file.getBytes());
		if(StringUtils.isNotBlank(strResponse)){
			json = JSON.parseObject(strResponse, JsonResult.class);
			if(json.isSuccess()) {
				json.put("state", "SUCCESS");
				json.put("title", file.getOriginalFilename());
				json.put("url", "download/" + json.getString("fileId"));
			}
		} else {
			json.setMessage("upload return message is blank");
		}
		json.put("uploadVo", uploadVo);
		
		logger.info("upload result:{}", json);
		return json;
	}
	
	
	@Post("doUpload")
	public Object doUpload(Invocation inv, MultipartFile file, UploadVo uploadVo) throws Throwable {
		return this.startUpload(inv, file, uploadVo);
	}
	
}
